<template>
  <div class="order-container">
    <van-nav-bar
      title="订单页"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />

    <van-address-list
      v-if="addrList.length > 0"
      :list="addrList"
      default-tag-text="默认"
      :switchable="false"
      @click-item="onAdd"
    />
    <van-contact-card v-else type="add" add-text="添加地址" @click="onAdd" />

    <div class="card-container">
      <van-card
        v-for="{ proid, num: cartNum, originprice, proname, img1 } in dataList"
        :key="proid"
        :num="cartNum"
        :price="originprice"
        :title="proname"
        :thumb="img1"
      />

      <van-empty v-if="dataList.length === 0" image="error" description="暂无订单" />
    </div>

    <div class="order-footer">
      <van-submit-bar
        :price="totalPrice"
        button-text="提交订单"
        @submit="onSubmit"
      ></van-submit-bar>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 实现方案备注： 使用sessionStorage 来传递已选中商品数据
import { Toast } from 'vant'
import { computed, onMounted, ref, type Ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 地址部分
// 默认地址数据
const addrList: Ref<any[]> = ref([])
const onAdd = () => {
  router.push('/address')
}

// 订单列表
// 提交商品列表数据
const dataList: Ref<any[]> = ref([])
onMounted(() => {
  dataList.value =
    JSON.parse(sessionStorage.getItem('selectedCartList') as string) || []
  // 尝试从本地存储中获取当前地址信息
  const currentAddr = sessionStorage.getItem('currentAddr')
  if (currentAddr) {
    addrList.value = [
      {
        ...JSON.parse(currentAddr),
      },
    ]
  }
})

// footer
const totalPrice = computed(() => {
  return dataList.value.length === 0
    ? 0
    : dataList.value.reduce((current, next) => {
        return current + next.originprice * next.num
      }, 0) * 100
})
const onSubmit = () => {
  Toast('提交订单' + '目前还未设置支付功能')
}
</script>

<style lang="scss" scoped>
.order-container {
  display: flex;
  height: 100%;
  flex-direction: column;
  .van-address-list {
    height: auto;
    padding-bottom: 20px;
    :deep(.van-address-list__bottom) {
      display: none;
    }
  }
  .card-container {
    flex: 1;
    overflow: auto;
    // background: lavender;
    padding: 0 0 18px;
  }

  .order-footer {
    height: 100px;
    .van-submit-bar {
      .van-submit-bar__text {
        text-align: left;
      }
    }
  }
}
</style>
